<template>
  <div id="ServerChild">
    <el-select v-if="showServer" v-model="server_id" placeholder="请选择服务器">
      <el-option
        v-for="(item, index) in ssoption"
        :label="item.label"
        :key="index"
        :value="item.value"
      ></el-option>
    </el-select>
    <el-select
      v-else
      v-model="serverIdArr"
      collapse-tags
      multiple
      @remove-tag="removeTag"
      placeholder="请选择服务器"
      @change="changeSelect"
    >
      <el-option
        label="全选"
        value="全选"
        @click.native="selectAll"
      ></el-option>
      <el-option
        v-for="(item, index) in ssoption"
        :label="item.label"
        :key="index"
        :value="item.value"
      ></el-option>
    </el-select>
  </div>
</template>
<script>
export default {
  name: "Select",
  props: {
    showServer: Boolean,
  },
  data() {
    return {
      server_id:"",
      serverIdArr: [],
      ssoption: [],
    };
  },
  mounted() {
    //获取服务器名称
    this.$http.get("/api/gmtool/getServer").then((res) => {
      res.data.result.forEach((item) => {
          let obj = {
            label: item.serverName,
            value: item.serverId,
          };
          this.ssoption.push(obj);
      });
    });
  },
  methods: {
    //全选功能实现
    selectAll() {
      if (this.serverIdArr.length < this.ssoption.length) {
        this.serverIdArr = [];
        this.ssoption.map((item) => {
          this.serverIdArr.push(item.value);
        });
        this.serverIdArr.unshift("全选");
      }else{
        this.serverIdArr = [];
      }
    },
    changeSelect(val) {
      if(!val.includes("全选") && val.length === this.ssoption.length){
        this.serverIdArr.unshift("全选");
      } else if(val.includes("全选") && val.length - 1<this.ssoption.length){
        this.serverIdArr = this.serverIdArr.filter((item) =>{
          return item!== "全选";
        });
      }
    },
    removeTag(val) {
      if (val === "全选"){
        this.serverIdArr = [];
      }
    },
  },
};
</script>
<style scoped>
</style>